import { ref } from 'vue'
import { login as loginApi } from '@/api/user'

/**
 * 登录服务
 */
export default function () {
  const loginLoading = ref(false)
  const loginForm = ref<{ password: string; phone: string; rememberMe: boolean; type: 1 | 2 }>({
    password: '',
    phone: '',
    rememberMe: false,
    type: 2,
  })
  const loginInfo = ref<{
    expireIn: number
    refreshToken: string
    tokenName: string
    tokenValue: string
  }>({
    expireIn: 0,
    refreshToken: '',
    tokenName: '',
    tokenValue: '',
  })

  const resetLoginForm = () => {
    loginForm.value = {
      password: '',
      phone: '',
      rememberMe: false,
      type: 2,
    }
  }

  const login = async () => {
    try {
      loginLoading.value = true
      const res = await loginApi(loginForm.value)
      loginLoading.value = false
      if (res.data.code === 20000) {
        loginInfo.value = res.data.data.row
        return ''
      }

      return res.data.message
    } catch (error) {
      loginLoading.value = false
      return '登录失败，请稍后重试'
    }
  }

  return {
    loginForm,
    loginLoading,
    loginInfo,
    login,
    resetLoginForm,
  }
}
